let code = JSON.parse(sessionStorage.getItem('code'));

import { Base64 } from 'js-base64';
import $http from '../../../servers/http';

export function getPublicKey() {
  $http
    .get({
      url: '/weathersms/sys/config/getkey',
    })
    .then(({ msg }) => {
      if (msg) {
        const codes = Base64.decode(msg);
        sessionStorage.setItem('code', codes);
        code = JSON.parse(sessionStorage.getItem('code'));
      }
    });
}

// 解密 值 私钥
export function doDecryptStr(enStr, privateKey) {
  const sm2 = require('sm-crypto').sm2;
  // 解密结果
  return sm2.doDecrypt(enStr, privateKey);
}

// sm2加密 值 公钥
export function doEncrypt(msgString, publicKey2) {
  const sm2 = require('sm-crypto').sm2;
  // 加密结果
  return sm2.doEncrypt(msgString, publicKey2);
}

// 传参加密
export function jsonDoEncrypt<T>(data: T) {
  if (code) {
    const str = JSON.stringify(data);
    const newStr = Base64.encode(str);
    const publicKey2 = doDecryptStr(code.secondAllPb, code.secondSecondPt);
    return doEncrypt(newStr, publicKey2);
  }
}
